import Vue from 'vue'
import Vuex from 'vuex'
import { getConnectionPoint } from '@/util/index.js'

Vue.use(Vuex)

// 初始化模拟数据
const initialState = {
  nodes: [
    {
      id: 'node1',
      title: '客户信息表',
      x: 100,
      y: 100,
      type: 'table',
      style: {
        width: 200,
        height: 150,
        backgroundColor: '#E3F2FD',
        borderColor: '#2196F3'
      },
      fields: [
        { name: 'customer_id', type: 'int', isPrimaryKey: true, isRequired: true },
        { name: 'customer_name', type: 'varchar(100)', isPrimaryKey: false, isRequired: true },
        { name: 'email', type: 'varchar(150)', isPrimaryKey: false, isRequired: true },
        { name: 'phone', type: 'varchar(20)', isPrimaryKey: false, isRequired: false },
        { name: 'address', type: 'text', isPrimaryKey: false, isRequired: false },
        { name: 'created_at', type: 'datetime', isPrimaryKey: false, isRequired: true }
      ]
    },
    {
      id: 'node2',
      title: '订单信息表',
      x: 450,
      y: 100,
      type: 'table',
      style: {
        width: 200,
        height: 180,
        backgroundColor: '#E8F5E8',
        borderColor: '#4CAF50'
      },
      fields: [
        { name: 'order_id', type: 'int', isPrimaryKey: true, isRequired: true },
        { name: 'customer_id', type: 'int', isPrimaryKey: false, isRequired: true },
        { name: 'order_date', type: 'datetime', isPrimaryKey: false, isRequired: true },
        { name: 'total_amount', type: 'decimal(10,2)', isPrimaryKey: false, isRequired: true },
        { name: 'status', type: 'varchar(20)', isPrimaryKey: false, isRequired: true }
      ]
    },
    {
      id: 'node3',
      title: '商品信息表',
      x: 800,
      y: 100,
      type: 'table',
      style: {
        width: 200,
        height: 160,
        backgroundColor: '#FFF3E0',
        borderColor: '#FF9800'
      },
      fields: [
        { name: 'product_id', type: 'int', isPrimaryKey: true, isRequired: true },
        { name: 'product_name', type: 'varchar(100)', isPrimaryKey: false, isRequired: true },
        { name: 'price', type: 'decimal(8,2)', isPrimaryKey: false, isRequired: true },
        { name: 'category', type: 'varchar(50)', isPrimaryKey: false, isRequired: false },
        { name: 'stock_quantity', type: 'int', isPrimaryKey: false, isRequired: true }
      ]
    },
    {
      id: 'node4',
      title: '订单详情表',
      x: 450,
      y: 350,
      type: 'table',
      style: {
        width: 200,
        height: 160,
        backgroundColor: '#F3E5F5',
        borderColor: '#9C27B0'
      },
      fields: [
        { name: 'order_detail_id', type: 'int', isPrimaryKey: true, isRequired: true },
        { name: 'order_id', type: 'int', isPrimaryKey: false, isRequired: true },
        { name: 'product_id', type: 'int', isPrimaryKey: false, isRequired: true },
        { name: 'quantity', type: 'int', isPrimaryKey: false, isRequired: true },
        { name: 'unit_price', type: 'decimal(8,2)', isPrimaryKey: false, isRequired: true }
      ]
    },
    {
      id: 'node5',
      title: '用户登录流程',
      x: 100,
      y: 400,
      type: 'process',
      style: {
        width: 200,
        height: 120,
        backgroundColor: '#FFEBEE',
        borderColor: '#F44336'
      },
      fields: [
        { name: 'username', type: 'string', isPrimaryKey: false, isRequired: true },
        { name: 'password', type: 'string', isPrimaryKey: false, isRequired: true }
      ]
    },
    {
      id: 'node6',
      title: '用户登录流程',
      x: 100,
      y: 600,
      type: 'process',
      style: {
        width: 200,
        height: 120,
        backgroundColor: '#FFEBEE',
        borderColor: '#F44336'
      },
      fields: [
        { name: 'username', type: 'string', isPrimaryKey: false, isRequired: true },
        { name: 'password', type: 'string', isPrimaryKey: false, isRequired: true }
      ]
    }
  ],
  connections: [
    {
      id: 'conn1',
      sourceNodeId: 'node1',
      targetNodeId: 'node2',
      sourcePoint: 'right',
      targetPoint: 'left',
      style: {
        strokeColor: '#2196F3',
        strokeWidth: 2
      }
    },
    {
      id: 'conn2',
      sourceNodeId: 'node2',
      targetNodeId: 'node3',
      sourcePoint: 'right',
      targetPoint: 'left',
      style: {
        strokeColor: '#4CAF50',
        strokeWidth: 2
      }
    },
    {
      id: 'conn3',
      sourceNodeId: 'node3',
      targetNodeId: 'node4',
      sourcePoint: 'bottom',
      targetPoint: 'right',
      style: {
        strokeColor: '#FF9800',
        strokeWidth: 2
      }
    },
    {
      id: 'conn4',
      sourceNodeId: 'node1',
      targetNodeId: 'node5',
      sourcePoint: 'bottom',
      targetPoint: 'top',
      style: {
        strokeColor: '#9C27B0',
        strokeWidth: 2
      }
    }
  ],
  newConnectionPath: null,
  targetPoints:[],
  targetXY:null,
  selectedNodeIds: [],
  scale: 1,
  panX: 0,
  panY: 0
}

export default new Vuex.Store({
  state: initialState,
  mutations: {
    // 更新节点位置
    UPDATE_NODE_POSITION(state, { nodeId, x, y }) {
      const node = state.nodes.find(n => n.id === nodeId)
      if (node) {
        // console.log('🔄 Store UPDATE_NODE_POSITION', {
        //   nodeId,
        //   oldPosition: { x: node.x, y: node.y },
        //   newPosition: { x, y }
        // })
        node.x = x
        node.y = y
      } else {
        console.error('❌ Node not found in store:', nodeId)
      }
    },
    // 选择节点
    SELECT_NODE(state, { nodeId, ctrlKey = false }) {
      if (nodeId === null) {
        // 清空所有选中
        state.selectedNodeIds = []
      } else if (ctrlKey) {
        // Ctrl多选模式
        if (state.selectedNodeIds.includes(nodeId)) {
          // 如果已选中，则取消选中
          state.selectedNodeIds.splice(state.selectedNodeIds.indexOf(nodeId), 1)
        } else {
          // 如果未选中，则添加到选中列表
          state.selectedNodeIds.push(nodeId)
        }
      } else {
        // 单选模式
        state.selectedNodeIds = [nodeId]
      }
      console.log('🔄 Store SELECT_NODE', state.selectedNodeIds);
    },
    // 添加连接线
    ADD_CONNECTION(state, connection) {
      //判断该链接线是否已经存在
      if (state.connections.some(c => c.sourceNodeId === connection.sourceNodeId && c.targetNodeId === connection.targetNodeId)) return
      state.connections.push(connection)
    },
    // 删除连接线
    REMOVE_CONNECTION(state, connectionId) {
      const index = state.connections.findIndex(c => c.id === connectionId)
      if (index > -1) {
        state.connections.splice(index, 1)
      }
    },
    // 添加节点
    ADD_NODE(state, node) {
      state.nodes.push(node)
    },
    // 删除节点
    REMOVE_NODE(state, nodeIds) {
      // 删除选中节点
      state.nodes = state.nodes.filter(node => !nodeIds.includes(node.id))
      // 删除相关连接线
      state.connections = state.connections.filter(
        c => !nodeIds.includes(c.sourceNodeId) && !nodeIds.includes(c.targetNodeId)
      )
      // 清空选中
      state.selectedNodeIds = []
    },
    // 更新画布缩放和平移
    UPDATE_CANVAS_TRANSFORM(state, { scale, panX, panY }) {
      state.scale = scale
      state.panX = panX
      state.panY = panY
    },
    UPDATE_NEW_CONNECTION_PATH(state, path) {
      state.newConnectionPath = path
    },
    //更新目标连接点坐标
    UPDATE_TARGET_POINTS(state, points) {
      state.targetPoints = points
    },
    //更新目标连接点坐标
    UPDATE_TARGET_XY(state, xy) {
      state.targetXY = xy
    }
  },
  actions: {
    updateNodePosition({ commit }, { nodeId, x, y }) {
      commit('UPDATE_NODE_POSITION', { nodeId, x, y })
    },
    selectNode({ commit }, { nodeId, ctrlKey = false }) {
      commit('SELECT_NODE', { nodeId, ctrlKey })
    },
    addConnection({ commit }, connection) {
      commit('ADD_CONNECTION', connection)
    },
    removeConnection({ commit }, connectionId) {
      commit('REMOVE_CONNECTION', connectionId)
    },
    addNode({ commit }, node) {
      commit('ADD_NODE', node)
    },
    addNodeToStore({ commit }, node) {
      commit('ADD_NODE', node)
    },
    removeNode({ commit }, nodeId) {
      commit('REMOVE_NODE', nodeId)
    },
    updateCanvasTransform({ commit }, transform) {
      commit('UPDATE_CANVAS_TRANSFORM', transform)
    },
    //更新链接线路径
    updateNewConnectionPath({ commit }, path) {
      commit('UPDATE_NEW_CONNECTION_PATH', path)
    },
    //更新目标连接点坐标
    updateTargetPoints({ commit }, points) {
      commit('UPDATE_TARGET_POINTS', points)
    },
    //更新目标连接点坐标
    updateTargetXY({ commit }, xy) {
      commit('UPDATE_TARGET_XY', xy)
    },
  },
  getters: {
    //获取新的链接线目标连接点坐标
    getNewConnectionPathTargetXY: (state) =>(node)=> {

      const targetXY = {  
        x: node.x + state.NewConnectionPath?.x || 0,
        y: node.y + state.NewConnectionPath?.y || 0
      }
      return targetXY
    },
    // 获取选中的节点
    selectedNodes: (state) => {
      return state.selectedNodeIds.map(id => state.nodes.find(n => n.id === id))
    },
    // 根据id获取节点
    getNodeById: (state) => (id) => {
      return state.nodes.find(n => n.id === id)
    },
    // 获取节点的连接
    getConnectionsByNodeId: (state) => (nodeId) => {
      return state.connections.filter(c => c.sourceNodeId === nodeId || c.targetNodeId === nodeId)
    }
  }
})